#include <iostream>
#include <winsock2.h>
#include <windows.h>
#include <mmsystem.h>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "winmm.lib")

#define RTP_PORT 5004
#define RTP_PACKET_SIZE 1024

int main() {
    WSADATA wsaData;
    WAVEFORMATEX wfx;
    BYTE* waveData = nullptr;
    DWORD waveSize = 0;
    SOCKET sock;
    sockaddr_in addr;

    // 初始化 Winsock
    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
        std::cerr << "WSAStartup failed" << std::endl;
        return 1;
    }

    // 读取 WAV 文件（与原 wav_player.cpp 类似）
    FILE* file = fopen("16bit_mono_44_1_khz.wav", "rb");
    if (!file) {
        std::cerr << "无法打开文件" << std::endl;
        return 1;
    }
    char chunkId[4];
    fread(chunkId, sizeof(char), 4, file);
    fseek(file, 4, SEEK_CUR);
    fread(chunkId, sizeof(char), 4, file);
    // ...略去格式校验...
    while (true) {
        fread(chunkId, sizeof(char), 4, file);
        DWORD chunkSize;
        fread(&chunkSize, sizeof(DWORD), 1, file);
        if (strncmp(chunkId, "fmt ", 4) == 0) {
            fread(&wfx, sizeof(WAVEFORMATEX), 1, file);
            fseek(file, chunkSize - sizeof(WAVEFORMATEX), SEEK_CUR);
            break;
        } else {
            fseek(file, chunkSize, SEEK_CUR);
        }
    }
    while (true) {
        fread(chunkId, sizeof(char), 4, file);
        DWORD chunkSize;
        fread(&chunkSize, sizeof(DWORD), 1, file);
        if (strncmp(chunkId, "data", 4) == 0) {
            waveSize = chunkSize;
            waveData = new BYTE[waveSize];
            fread(waveData, sizeof(BYTE), waveSize, file);
            break;
        } else {
            fseek(file, chunkSize, SEEK_CUR);
        }
    }
    fclose(file);

    // 创建 UDP socket
    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock == INVALID_SOCKET) {
        std::cerr << "socket 创建失败" << std::endl;
        return 1;
    }
    addr.sin_family = AF_INET;
    addr.sin_port = htons(RTP_PORT);
    addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 本地测试

    // 分包发送音频数据
    DWORD sent = 0;
    // 计算每包的实际播放时长（毫秒）
    double ms_per_packet = (double)RTP_PACKET_SIZE / wfx.nAvgBytesPerSec * 1000.0;
    DWORD startTick = GetTickCount();
    DWORD pktCount = 0;
    while (sent < waveSize) {
        int pktSize = (waveSize - sent > RTP_PACKET_SIZE) ? RTP_PACKET_SIZE : (waveSize - sent);
        int ret = sendto(sock, (const char*)(waveData + sent), pktSize, 0, (sockaddr*)&addr, sizeof(addr));
        if (ret == SOCKET_ERROR) {
            std::cerr << "发送失败" << std::endl;
            break;
        }
        sent += pktSize;
        pktCount++;
        // 精确限速，保证每秒发送的字节数与音频速率一致
        DWORD elapsed = GetTickCount() - startTick;
        DWORD expectedElapsed = (DWORD)(pktCount * ms_per_packet);
        if (expectedElapsed > elapsed) {
            Sleep(expectedElapsed - elapsed);
        }
    }
    std::cout << "发送完成" << std::endl;
    closesocket(sock);
    WSACleanup();
    delete[] waveData;
    return 0;
}
